<template>
  <div id="app">
    <!-- 根据登录状态和页面状态显示不同组件 -->
    <UserLogin 
      v-if="!isLoggedIn && currentPage === 'login'" 
      @loginSuccess="handleLoginSuccess" 
      @switchToRegister="handleSwitchToRegister"
    />
    <UserRegister 
      v-else-if="!isLoggedIn && currentPage === 'register'" 
      @registerSuccess="handleRegisterSuccess"
      @switchToLogin="handleSwitchToLogin"
    />
    <VoiceChat v-else @logout="handleLogout" />
  </div>
</template>

<script>
import UserLogin from './components/UserLogin.vue'
import UserRegister from './components/UserRegister.vue'
import VoiceChat from './components/VoiceChat.vue'
import { authApi } from './api/index.js'

export default {
  name: 'App',
  components: {
    UserLogin,
    UserRegister,
    VoiceChat
  },
  data() {
    return {
      isLoggedIn: false,
      currentPage: 'login' // 'login' 或 'register'
    }
  },
  mounted() {
    // 检查是否已登录
    this.checkLoginStatus()
  },
  methods: {
    // 检查登录状态
    async checkLoginStatus() {
      const token = localStorage.getItem('token')
      console.log('=== App.vue checkLoginStatus ===')
      console.log('localStorage中的token:', token)
      
      if (!token) {
        console.log('没有token，用户未登录')
        this.isLoggedIn = false
        return
      }
      
      try {
        // 验证token有效性
        console.log('验证token有效性...')
        await authApi.getCurrentUser()
        console.log('token验证成功，用户已登录')
        this.isLoggedIn = true
      } catch (error) {
        console.log('token验证失败:', error.message)
        // token无效，清除本地存储
        localStorage.removeItem('token')
        this.isLoggedIn = false
      }
    },
    handleLoginSuccess(result) {
      console.log('登录成功:', result)
      this.isLoggedIn = true
      this.currentPage = 'login'
    },
    handleLogout() {
      console.log('用户退出登录')
      this.isLoggedIn = false
      this.currentPage = 'login'
    },
    handleSwitchToRegister() {
      console.log('切换到注册页面')
      this.currentPage = 'register'
    },
    handleSwitchToLogin() {
      console.log('切换到登录页面')
      this.currentPage = 'login'
    },
    handleRegisterSuccess(result) {
      console.log('注册成功:', result)
      // 注册成功后切换到登录页面
      this.currentPage = 'login'
    }
  }
}
</script>

<style>
#app {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  height: 100vh;
  margin: 0;
  padding: 0;
}

/* 全局样式重置 */
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
  height: 100vh;
  overflow: hidden;
}

html {
  height: 100vh;
}
</style>
